package com.gitee.jwds666.fs.utils;


import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;

import java.io.File;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

public class FileTypeUtils {

    private static Map<String,FileType> SUFFIX_TYPE;
    private static Map<String,FileType> MEDIA_TYPE_MAP;
    static FileType folder = new FileType("文件夹","folder",true);
    static FileType other= new FileType("文件","file",true);
    static FileType zip= new FileType("压缩文件","file-archive-o",true);
    static FileType audio= new FileType("音频文件","file-audio-o",true);
    static FileType excel= new FileType("excel文件","file-excel-o",true);
    static FileType image= new FileType("图片文件","file-image-o",true);
    static FileType video= new FileType("视频文件","file-video-o",true);
    static FileType pdf= new FileType("pdf文件","file-pdf-o",true);
    static FileType text= new FileType("文本文件","file-text-o",true);
    static FileType word= new FileType("word文件","file-word-o",true);
    static{


        SUFFIX_TYPE = new LinkedHashMap<>();
        SUFFIX_TYPE.put(".zip",zip);
        SUFFIX_TYPE.put(".rar",zip);
        SUFFIX_TYPE.put(".7z",zip);
        SUFFIX_TYPE.put(".jar",zip);
        SUFFIX_TYPE.put(".war",zip);
        SUFFIX_TYPE.put(".xls",excel);
        SUFFIX_TYPE.put(".xlsx",excel);
        SUFFIX_TYPE.put(".pdf",pdf);
        SUFFIX_TYPE.put(".doc",word);
        SUFFIX_TYPE.put(".docx",word);


        MEDIA_TYPE_MAP = new HashMap<>();
        MEDIA_TYPE_MAP.put("image",image);
        MEDIA_TYPE_MAP.put("audio",audio);
        MEDIA_TYPE_MAP.put("video",video);
        MEDIA_TYPE_MAP.put("text",text);
    }

    private static FileType fileType(File file){
        if (file.isDirectory())return folder;
        String suffix = FileUtils.getFileSuffix(file);
        FileType fileType = SUFFIX_TYPE.get(suffix);
        if (fileType == null){
            MediaType mediaType = getMediaType(file);
            fileType = MEDIA_TYPE_MAP.get(mediaType.getType());
        }
        if (fileType == null){
            if (suffix.isEmpty()){
                fileType = new FileType("文件","file",true);
            }else{
                fileType = new FileType(suffix.substring(1)+"文件","file",true);
            }
        }

        return fileType;
    }
    public static String getFileType(File file){
        return fileType(file).getName();
    }

    public static String getFileTypeIcon(File file){
        return fileType(file).getIcon();
    }

    public static boolean getFileOpenFlag(File file){
        return fileType(file).isOpenFlag();
    }


    public static MediaType getMediaType(File file){
        MediaType mediaType = null;
        try {
            mediaType = MediaTypeFactory.getMediaType(file.getName()).get();
        }catch (Exception e){
            mediaType = MediaType.APPLICATION_OCTET_STREAM;
        }
        return mediaType;
    }
}
